package com.ghsc.ghxc.jsb.ui.message.fragment

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastClickListener
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentSearchGroupChatBinding
import com.ghsc.ghxc.jsb.ui.message.activity.SearchChatViewModel
import com.ghsc.ghxc.jsb.ui.message.adapter.GroupTypeAdapter
import com.ghsc.ghxc.jsb.ui.message.bean.GroupTypeItem
import com.ghsc.ghxc.jsb.ui.message.bean.GroupTypeList
import com.ghsc.ghxc.jsb.ui.message.bean.SearchChatDataBean
import com.ghsc.ghxc.jsb.view.NotDataView
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.fragment
 * 类名：SearchGroupChatFragment
 * 创建时间：2024/5/9 19:06
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class SearchGroupChatFragment   : BaseVMFragment<SearchChatViewModel, FragmentSearchGroupChatBinding>(
    R.layout.fragment_search_group_chat){
    override fun attachVMClass(): Class<SearchChatViewModel>? {
        return SearchChatViewModel::class.java
    }

    override fun lazyLoad() {
    }
    companion object {
        fun getInstance(): SearchGroupChatFragment? {
            return SearchGroupChatFragment()
        }
    }

    var isInitFirst :Boolean=true
    private val mAdapter: SearchChatAdapter by lazy { SearchChatAdapter() }
    var mList = arrayListOf<SearchChatDataBean>()
    private var notDataView: View? = null
    var keyword:String=""
    var classify_id:String =""

    var itemPosition =-1


    //分类
    private val mTypeAdapter: GroupTypeAdapter by lazy { GroupTypeAdapter() }
    var mTypeList = arrayListOf<GroupTypeItem>()

    override fun initView(savedInstanceState: Bundle?) {
        binding.rvList.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(requireActivity(), binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->
        }
        mAdapter.addChildClickViewIds(R.id.tvBtnNext)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id==R.id.tvBtnNext){
                if (mAdapter.getItem(position).isClick){
                    showToast("您已申请...")
                }else{
                    itemPosition=position
                    // 加入群
                    val map: HashMap<String, Any> = HashMap()
                    map["gid"] = mAdapter.getItem(position).gid
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onJoinGroupMethod(it1) }
                }

            }
        }
        initRefreshLayout()
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    override fun initData() {
        super.initData()
        val configBean= UserManager.getConfig()
        configBean?.let {
//            GroupTypeList
            var sysConfigResultData = it.getSysConfigBean(CustKey.configK52 )
            if(sysConfigResultData!=null)
            if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                var groupTypeList=GsonUtil.GsonToJsonClass(sysConfigResultData.cfg_value, GroupTypeList::class.java)
                if (groupTypeList.size>0){
                    binding.rvListType.visibility= View.VISIBLE
                    binding.rvListType.layoutManager = LinearLayoutManager(
                        requireActivity(),
                        LinearLayoutManager.HORIZONTAL,
                        false
                    )
                    binding.rvListType.adapter = mTypeAdapter
                    for (i in groupTypeList.indices){
                        groupTypeList[i].isSelect = i==0
                    }
                    mTypeAdapter.replaceData(groupTypeList)
                    classify_id=groupTypeList[0].classify_id.toString()
                    pageNo = 1
                    getListData()
                    mTypeAdapter.setOnFastClickListener { data, position ->
                        for (i in mTypeAdapter.data.indices){
                            mTypeAdapter.data[i].isSelect = i==position
                        }
                        classify_id=mTypeAdapter.getItem(position).classify_id.toString()
                        mTypeAdapter.notifyDataSetChanged()
                        pageNo = 1
                        getListData()
                    }
                }
            }


        }
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnClose.setSingleClickListener {
            keyword=""
            binding.etSearch.setText("")
        }
        binding.tvBtnNext.setOnClickListener {
            keyword = binding.etSearch.text.toString().trim()
            binding.etSearch.clearFocus()
            hideKeyboard(binding.etSearch)
            if(!TextUtils.isEmpty(keyword)){
                for (i in mTypeAdapter.data.indices){
                    mTypeAdapter.data[i].isSelect = false
                }
                classify_id=""
                mTypeAdapter.notifyDataSetChanged()
                pageNo = 1
                getListData()
            }else{
                pageNo = 1
                getListData()
            }
        }

        binding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(
                v: TextView,
                actionId: Int,
                event: KeyEvent?
            ): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    hideKeyboard(v)
                    // 搜索，进行自己要的操作...
                    if (binding.etSearch.text.toString().trim().isNotEmpty()){
                        for (i in mTypeAdapter.data.indices){
                            mTypeAdapter.data[i].isSelect = false
                        }
                        classify_id=""
                        mTypeAdapter.notifyDataSetChanged()
                        keyword = binding.etSearch.text.toString().trim()
                        pageNo = 1
                        getListData()
                    }else{
                        keyword =""
                        if (TextUtils.isEmpty(classify_id)) {
                            classify_id=mTypeAdapter.data[0].classify_id.toString()
                            mTypeAdapter.data[0].isSelect=true
                            mTypeAdapter.notifyDataSetChanged()
                        }
                        pageNo = 1
                        getListData()
                    }
                    return true
                }
                return false
            }
        })
        binding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                if(TextUtils.isEmpty(p0.toString().trim())){
                    keyword =""
                    if (TextUtils.isEmpty(classify_id)) {
                        classify_id=mTypeAdapter.data[0].classify_id.toString()
                        mTypeAdapter.data[0].isSelect=true
                        mTypeAdapter.notifyDataSetChanged()
                    }
                    pageNo = 1
                    getListData()
                }
            }

        })
    }
    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword
        map["classify_id"] = classify_id
        loge("xx="+ GsonUtil.mapToJsonStrObj(map).toString())
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSearchGroupMethod(it1) }
    }
    /** 隐藏软键盘 **/
    protected open fun hideKeyboard(view: View) {
        val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@SearchGroupChatFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(it)
            }
            againLoginMsg.observe(this@SearchGroupChatFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()

            }

            onJoinGroupData.observe(this@SearchGroupChatFragment){
                showToast("申请成功")
                if (itemPosition>-1){
                    mAdapter.getItem(itemPosition).isClick=true
                }
                mAdapter.notifyItemChanged(itemPosition)
            }
            onSearchGroupData.observe(this@SearchGroupChatFragment) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.isNullOrEmpty()){
                        mAdapter.replaceData( it.data)
                        mAdapter.setEmptyView(notDataView!!)
                        if (!isInitFirst)
                            showToast(it.msg)
                        isInitFirst=false
                    } else {
                        mAdapter.replaceData( it.data)
                    }
                } else {
                    if (!it.data.isNullOrEmpty())
                        mAdapter.addData(it.data!!)
                }
            }

        }
    }


    inner class SearchChatAdapter   : BaseQuickAdapter<SearchChatDataBean, BaseViewHolder>(
        R.layout.search_chat_item) {
        override fun convert(helper: BaseViewHolder, item: SearchChatDataBean) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.headimg))
            helper.setText(R.id.name,item.name)
                .setText(R.id.usercnt,item.usercnt.toString()+"/"+item.maxcnt)
                .setText(R.id.gonggao,item.gonggao)
                .setGone(R.id.tvBtnNext, item.isHave)
                .setText(R.id.tvBtnNext,if(item.isClick) "已申请" else  "加入群")
        }
    }

}